<template>
  <view class="search-bar">
    <!-- 搜索输入框 -->
    <view class="search-input-container">
      <BaseIcon
        name="i-carbon-search"
        size="small"
        class="search-icon"
      />

      <input
        ref="searchInput"
        v-model="searchValue"
        :class="inputClass"
        :placeholder="placeholder"
        :disabled="disabled"
        @focus="handleFocus"
        @blur="handleBlur"
        @input="handleInput"
        @confirm="handleSearch"
      />

      <!-- 清空按钮 -->
      <BaseIcon
        v-if="searchValue && !disabled"
        name="i-carbon-close"
        size="small"
        class="clear-icon"
        clickable
        @click="handleClear"
      />
    </view>

    <!-- 取消按钮 -->
    <BaseButton
      v-if="showCancel && isFocused"
      type="ghost"
      size="small"
      @click="handleCancel"
    >
      取消
    </BaseButton>

    <!-- 筛选按钮 -->
    <slot name="filter">
      <BaseButton
        v-if="showFilter"
        type="ghost"
        size="small"
        @click="handleFilter"
      >
        <template #prefix>
          <BaseIcon name="i-carbon-filter" size="small" />
        </template>
        筛选
      </BaseButton>
    </slot>
  </view>

  <!-- 搜索建议 -->
  <view v-if="showSuggestions && suggestions.length > 0" class="search-suggestions">
    <view
      v-for="(suggestion, index) in suggestions"
      :key="index"
      class="suggestion-item"
      @click="handleSuggestionClick(suggestion)"
    >
      <BaseIcon name="i-carbon-search" size="small" class="suggestion-icon" />
      <text class="suggestion-text">{{ suggestion }}</text>
      <BaseIcon
        name="i-carbon-arrow-up-left"
        size="small"
        class="suggestion-arrow"
      />
    </view>
  </view>

  <!-- 搜索历史 -->
  <view v-if="showHistory && searchHistory.length > 0 && !searchValue" class="search-history">
    <view class="history-header">
      <text class="history-title">搜索历史</text>
      <BaseIcon
        name="i-carbon-trash-can"
        size="small"
        clickable
        @click="handleClearHistory"
      />
    </view>

    <view class="history-list">
      <view
        v-for="(item, index) in searchHistory"
        :key="index"
        class="history-item"
        @click="handleHistoryClick(item)"
      >
        <BaseIcon name="i-carbon-time" size="small" class="history-icon" />
        <text class="history-text">{{ item }}</text>
        <BaseIcon
          name="i-carbon-close"
          size="small"
          class="history-delete"
          clickable
          @click.stop="handleDeleteHistoryItem(index)"
        />
      </view>
    </view>
  </view>

  <!-- 热门搜索 -->
  <view v-if="showHotSearch && hotSearches.length > 0 && !searchValue" class="hot-search">
    <view class="hot-header">
      <text class="hot-title">热门搜索</text>
    </view>

    <view class="hot-list">
      <view
        v-for="(item, index) in hotSearches.slice(0, 10)"
        :key="index"
        class="hot-item"
        @click="handleHotClick(item)"
      >
        <text class="hot-rank" :class="getRankClass(index)">{{ index + 1 }}</text>
        <text class="hot-text">{{ item }}</text>
      </view>
    </view>
  </view>
</template>

<script setup lang="ts">
import { ref, computed, nextTick, watch } from 'vue'
import BaseIcon from '../ui/BaseIcon.vue'
import BaseButton from '../ui/BaseButton.vue'

interface Props {
  // 占位符文字
  placeholder?: string
  // 是否禁用
  disabled?: boolean
  // 是否显示取消按钮
  showCancel?: boolean
  // 是否显示筛选按钮
  showFilter?: boolean
  // 是否显示搜索建议
  showSuggestions?: boolean
  // 是否显示搜索历史
  showHistory?: boolean
  // 是否显示热门搜索
  showHotSearch?: boolean
  // 搜索建议列表
  suggestions?: string[]
  // 搜索历史列表
  searchHistory?: string[]
  // 热门搜索列表
  hotSearches?: string[]
  // 最大历史记录数
  maxHistoryItems?: number
  // 自定义类名
  customClass?: string
}

const props = withDefaults(defineProps<Props>(), {
  placeholder: '搜索小说、作者',
  disabled: false,
  showCancel: false,
  showFilter: false,
  showSuggestions: false,
  showHistory: true,
  showHotSearch: true,
  suggestions: () => [],
  searchHistory: () => [],
  hotSearches: () => [],
  maxHistoryItems: 10,
  customClass: '',
})

const emit = defineEmits<{
  search: [value: string]
  input: [value: string]
  focus: []
  blur: []
  clear: []
  cancel: []
  filter: []
  suggestionClick: [suggestion: string]
  historyClick: [item: string]
  hotClick: [item: string]
  clearHistory: []
}>()

// 响应式数据
const searchValue = ref('')
const isFocused = ref(false)
const searchInput = ref()

// 输入框样式
const inputClass = computed(() => {
  const baseClass = 'search-input flex-1 text-text-primary bg-transparent outline-none'

  return baseClass
})

// 获取排名样式
const getRankClass = (index: number) => {
  if (index < 3) {
    return 'hot-rank-top'
  }
  return 'hot-rank-normal'
}

// 处理输入
const handleInput = (event: any) => {
  const value = event.detail.value
  searchValue.value = value
  emit('input', value)
}

// 处理搜索
const handleSearch = () => {
  if (searchValue.value.trim()) {
    emit('search', searchValue.value.trim())
  }
}

// 处理焦点
const handleFocus = () => {
  isFocused.value = true
  emit('focus')
}

const handleBlur = () => {
  // 延迟失去焦点，避免点击其他元素时过早隐藏
  setTimeout(() => {
    isFocused.value = false
    emit('blur')
  }, 200)
}

// 处理清空
const handleClear = () => {
  searchValue.value = ''
  emit('clear')
}

// 处理取消
const handleCancel = () => {
  searchValue.value = ''
  isFocused.value = false
  emit('cancel')
}

// 处理筛选
const handleFilter = () => {
  emit('filter')
}

// 处理建议点击
const handleSuggestionClick = (suggestion: string) => {
  searchValue.value = suggestion
  emit('suggestionClick', suggestion)
  emit('search', suggestion)
}

// 处理历史点击
const handleHistoryClick = (item: string) => {
  searchValue.value = item
  emit('historyClick', item)
  emit('search', item)
}

// 处理热门点击
const handleHotClick = (item: string) => {
  searchValue.value = item
  emit('hotClick', item)
  emit('search', item)
}

// 处理清空历史
const handleClearHistory = () => {
  emit('clearHistory')
}

// 处理删除历史项
const handleDeleteHistoryItem = (index: number) => {
  // 这里可以通过emit告知父组件删除特定历史项
  console.log('Delete history item:', index)
}

// 聚焦输入框
const focus = () => {
  nextTick(() => {
    if (searchInput.value) {
      searchInput.value.focus()
    }
  })
}

// 暴露方法
defineExpose({
  focus,
})
</script>

<style scoped>
.search-bar {
  @apply flex items-center gap-2;
}

.search-input-container {
  @apply flex-1 flex items-center gap-2 bg-bg-light rounded-custom px-3 py-2;
}

.search-icon {
  @apply text-text-muted;
}

.search-input {
  @apply flex-1 text-text-primary bg-transparent outline-none text-base;
}

.clear-icon {
  @apply text-text-muted;
}

.search-suggestions {
  @apply mt-2 bg-bg-medium rounded-custom shadow-md overflow-hidden;
}

.suggestion-item {
  @apply flex items-center gap-3 px-md py-sm border-b border-custom last:border-b-0;
  @apply transition-colors duration-200 cursor-pointer;
}

.suggestion-item:hover {
  @apply bg-bg-light;
}

.suggestion-icon {
  @apply text-text-muted;
}

.suggestion-text {
  @apply flex-1 text-text-primary;
}

.suggestion-arrow {
  @apply text-text-muted;
}

.search-history {
  @apply mt-4;
}

.history-header {
  @apply flex items-center justify-between mb-sm;
}

.history-title {
  @apply text-sm font-medium text-text-primary;
}

.history-list {
  @apply space-y-2;
}

.history-item {
  @apply flex items-center gap-3 p-sm bg-bg-light rounded-custom cursor-pointer;
  @apply transition-colors duration-200;
}

.history-item:hover {
  @apply bg-bg-medium;
}

.history-icon {
  @apply text-text-muted;
}

.history-text {
  @apply flex-1 text-text-secondary;
}

.history-delete {
  @apply text-text-muted;
}

.hot-search {
  @apply mt-4;
}

.hot-header {
  @apply mb-sm;
}

.hot-title {
  @apply text-sm font-medium text-text-primary;
}

.hot-list {
  @apply flex flex-wrap gap-2;
}

.hot-item {
  @apply flex items-center gap-2 px-3 py-2 bg-bg-light rounded-custom cursor-pointer;
  @apply transition-colors duration-200;
}

.hot-item:hover {
  @apply bg-bg-medium;
}

.hot-rank {
  @apply text-sm font-bold;
}

.hot-rank-top {
  @apply text-novel-primary;
}

.hot-rank-normal {
  @apply text-text-muted;
}

.hot-text {
  @apply text-sm text-text-secondary;
}
</style>